import { SupplierPriceService } from './../../../../@core/services/supplierPrice/supplier-price.service';
import { CustomerService } from 'src/app/@core/services/customer/customer.service';
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import {
  DialogService,
  DValidateRules,
  FormLayout,
  TableWidthConfig,
} from 'ng-devui';
import { PurchaseOrder } from 'src/app/@core/data/purchase';
import { PurchaseService } from 'src/app/@core/services/purchase/purchase.service';
import { UserService } from 'src/app/@core/services/user/user.service';
import { AttachmentComponent } from 'src/app/@shared/components/attachment/attachment.component';
import { SelectMaterialComponent } from 'src/app/@shared/components/select-material/select-material.component';
import { SelectSupplierComponent } from 'src/app/@shared/components/select-supplier/select-supplier.component';
import { SelectUserComponent } from 'src/app/@shared/components/select-user/select-user.component';
import { environment } from 'src/environments/environment';
import { SelectRequireComponent } from '../select-require/select-require.component';
import { EncodeRulesService } from 'src/app/@core/services/encoderRule/encode-rules.service';
import { StorehouseService } from 'src/app/@core/services/storehouse/storehouse.service';
import { ReviewRolesService } from 'src/app/@core/services/ReviewRoles/review-roles.service';
import { SelectLogisticsComponent } from 'src/app/@shared/components/select-logistics/select-logistics.component';

@Component({
  selector: 'app-purchase-order-add',
  templateUrl: './purchase-order-add.component.html',
  styleUrls: ['./purchase-order-add.component.scss'],
})
export class PurchaseOrderAddComponent {
  Math = Math;
  msgs: Array<Object> = [];
  UrlHead: any = environment.modifiedApiUrl;
  layoutDirection: FormLayout = FormLayout.Horizontal;
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: '操作',
      width: '150px',
    },
    {
      field: '物料编码',
      width: '150px',
    },
    {
      field: '图片',
      width: '150px',
    },
    {
      field: '物料名称',
      width: '150px',
    },
    {
      field: '物料规格',
      width: '150px',
    },
    {
      field: '物料描述',
      width: '150px',
    },
    {
      field: '物料单位',
      width: '150px',
    },
    {
      field: '是否检验',
      width: '200px',
    },
    {
      field: '实时库存',
      width: '150px',
    },
    {
      field: '采购数量',
      width: '200px',
    },
    {
      field: '预计到货日期',
      width: '200px',
    },
    {
      field: '单价(含税)',
      width: '200px',
    },
    {
      field: '税率',
      width: '200px',
    },
    {
      field: '不含税单价',
      width: '150px',
    },
    {
      field: '含税金额',
      width: '150px',
    },
    {
      field: '不含税金额',
      width: '150px',
    },
    {
      field: '税额',
      width: '150px',
    },

    {
      field: '来源单号',
      width: '200px',
    },
    {
      field: '备注',
      width: '150px',
    },
  ]; //表格宽度配置
  taxRate: number = 13;
  customerContact: any;
  loadData: boolean;
  purchaseOrder: PurchaseOrder = {
    purchaseOrderId: null, // 采购订单ID
    purchaseOrderNum: '', // 采购订单单号
    orderDate: new Date(), // 单据日期
    poSupplyId: 0, // 供应商ID
    supplyShortName: '', // 供应商简称
    supplyChineseName: '', // 供应商中文名
    supplyEnglishName: '', // 供应商英文名
    supplyContactId: 0, // 供应商联系人Id
    supplyContactName: '', // 供应商联系人名称
    address: '', // 收料地址
    purchaseManId: 0, // 业务员Id
    purchaseManName: '', // 业务员名称
    departmentId: 0, // 部门Id
    departmentName: '', // 部门名称
    supplySettlementMethodId: 0, // 结算方式ID
    settlementMethodName: '', // 结算方式名称
    supplyCurrencyId: 0, // 交易币种ID
    currencyName: '', // 交易币种名称
    supplyCollectionPeriodId: 0, // 付款账期ID
    collectionPeriodName: '', // 付款账期名称
    remark: '', // 备注
    status: '未开始审核', // 状态
    isClosed: false, // 是否结案
    files: [], // 附件
    fileRemarks: [], // 附件备注
    creator: '', // 制单人
    createDate: null, // 制单日期
    logisticsCompanyCode: '', // 物流公司编码
    logisticsCompanyName: '', // 物流公司名称
    logisticsTrackingNum: '', // 物流单号
    logisticsContactName: '', // 物流联系人
    logisticsContactPhone: '', // 物流联系人电话
    logisticsFee: 0, // 物流费用
    purchaseOrderParts: [
      {
        purchaseOrderPartId: null, // 采购订单物料行ID
        partNum: '', // 物料编号
        partUOM: '', // 物料单位
        partName: '', // 物料名称
        description: '', // 物料描述
        partType: '', // 规格型号
        image: '', // 图片
        purchaseQuantity: 0, // 采购数量
        realTimeInventory: 0, // 实时库存
        estimatedDeliveryDate: null, // 预计到货日期
        priceWithTax: 0, // 单价（含税）
        priceWithoutTax: 0, // 单价（不含税）
        taxRate: 0, // 税率
        amountWithTax: 0, // 含税金额
        amountWithoutTax: 0, // 不含税金额
        taxAmount: 0, // 税额
        poPartId: 0, // 物料ID
        receivedQuantity: 0, // 已入库数
        noReceivedQuantity: 0, // 未入库数
        deliveryQuantity: 0, // 已到货数
        note: '', // 备注
        purchasereQuireNum: '', // 来源采购订单单号
        poPurchaseOrderId: null, // 采购订单ID
        purchaseRequiredOrderPartId: null, // 采购订物料行ID
        purchaseOrderNum: '',
        isInspection: false,
        qrCodePath: ''
      },
    ],
    supplyNum: '',
    totalReceivedQuantity: 0,
    totalNotReceivedQuantity: 0,
    totalPurchaseQuantity: 0,
    totalaMountWithTax: 0,
    totalTaxAmount: 0,
    totalAmountWithoutTax: 0
  };
  purchaseOrderRules: { [key: string]: DValidateRules } = {
    purchaseOrderNum: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*采购订单单号不能为空' },
        { minlength: 2, message: '*采购订单单号长度至少为2' },
        { maxlength: 40, message: '*采购订单单号长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*采购订单单号不能包含空格' },
      ],
    },
    purchaseManName: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*业务员不能为空' }],
    },
    supply: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*供应商不能为空' }],
    },
    advicePurchaseDate: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*时间不能为空' }],
    },
    partNum: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*物料不能为空' }],
    },
    purchaseDate: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*建议采购时间不能为空' }],
    },
    purchaseQuantity: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*建议采购数量不能为空' }],
    },
  };
  options = [
    { label: '检验', value: true },
    { label: '不检验', value: false }
  ]
  supplyContactOption = []; // 供应商联系人
  supplyContact = {}; //供应商联系人
  settlementMethodOption = []; // 结算方式
  settlementMethod = {}; //结算方式
  currencyOption = []; // 交易币种
  currency = {}; //交易币种
  collectionPeriodOption = []; // 付款账期
  collectionPeriod = {}; //付款账期
  fujianNumber: any = 0;
  defaultTaxRate = 0;
  constructor(
    private DialogService: DialogService,
    private Router: Router,
    private UserService: UserService,
    private PurchaseService: PurchaseService,
    private CustomerService: CustomerService,
    private SupplierPriceService: SupplierPriceService,
    private EncodeRulesService: EncodeRulesService,
    private StorehouseService: StorehouseService,
    private ReviewFlowService: ReviewRolesService
  ) {}
  ngOnInit(): void {
    this.EncodeRulesService.GenerateWarehouseCodeRule(
      '采购订单',
      '采购订单'
    ).subscribe((data: any) => {
      this.purchaseOrder.purchaseOrderNum = data;
    });
    const userinfoString = localStorage.getItem('userinfo');
    if (userinfoString) {
      this.purchaseOrder.creator = JSON.parse(userinfoString).username;
    }
    this.CustomerService.GetPagedCurrency(1, 9999).subscribe((res: any) => {
      this.currencyOption = res.items;
    });
    this.CustomerService.GetPagedCollectionPeriod({
      PageSize: 999,
      PageNumber: 1,
      SearchStatus: '付款',
    }).subscribe((res: any) => {
      this.collectionPeriodOption = res.items;
    });
    this.CustomerService.GetPagedSettlementMethod(1, 9999).subscribe(
      (res: any) => {
        this.settlementMethodOption = res.items;
      }
    );
  }
  selectMaterial(rowItem: any, dialogtype?: string) {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: '',
      title: '选择物料',
      content: SelectMaterialComponent,
      dialogtype: dialogtype,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            rowItem.poPartId = results.modalContentInstance.selectData.partId;
            rowItem.partNum = results.modalContentInstance.selectData.partNum;
            rowItem.partName = results.modalContentInstance.selectData.partName;
            rowItem.partUOM = results.modalContentInstance.selectData.partUOM;
            rowItem.partType = results.modalContentInstance.selectData.partType;
            rowItem.image = results.modalContentInstance.selectData.fileURL;
            rowItem.purchaseRequiredOrderPartId = null;
            rowItem.purchasereQuireNum = '';
            rowItem.taxRate = this.defaultTaxRate;
            rowItem.isInspection = results.modalContentInstance.selectData.isInspection;
            rowItem.description =
              results.modalContentInstance.selectData.description;
            this.SupplierPriceService.getVaildPriceByPartId(
              rowItem.poPartId
            ).subscribe(
              (res: any) => {
                rowItem.priceWithTax = res[0].price;
                this.calculateAmount(rowItem);
              },
              (error: any) => {
                rowItem.priceWithTax = 0;
                this.calculateAmount(rowItem);
              }
            );
            this.StorehouseService.GetPartsAllInventory([
              rowItem.poPartId,
            ]).subscribe((res: any) => {
              rowItem.realTimeInventory = res[0].inventory;
            });

            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  } //提示框
  addRow() {
    this.purchaseOrder.purchaseOrderParts.push({
      purchaseOrderPartId: 0,
      partNum: '',
      partUOM: '',
      partName: '',
      description: '',
      partType: '',
      image: '',
      realTimeInventory: 0,
      purchaseQuantity: 0,
      estimatedDeliveryDate: null,
      priceWithTax: 0,
      priceWithoutTax: 0,
      taxRate: this.defaultTaxRate,
      amountWithTax: 0,
      amountWithoutTax: 0,
      taxAmount: 0,
      poPartId: 0,
      receivedQuantity: 0,
      noReceivedQuantity: 0,
      deliveryQuantity: 0,
      note: '',
      purchasereQuireNum: '',
      purchaseRequiredOrderPartId: 0,
      poPurchaseOrderId: 0,
      purchaseOrderNum: '',
      isInspection: false,
      qrCodePath: ''
    });
  } //添加行
  deleteRow(index: number) {
    this.purchaseOrder.purchaseOrderParts.splice(index, 1);
    if (this.purchaseOrder.purchaseOrderParts.length == 0) {
      this.addRow();
    }
    this.purchaseOrder.purchaseOrderParts.map((item: any) => {
      this.calculateAmount(item);
    });
  }
  isStartApproval: boolean = false;
  isStartApprovalChange() {
    this.isStartApproval = true;
  }
  submit($event: any) {
    if ($event.valid) {
      if (!this.validateSalesQuotation(this.purchaseOrder)) {
        return;
      }
      this.purchaseOrder.createDate = new Date();
      this.purchaseOrder.purchaseOrderParts.forEach((item) => {
        item.purchaseOrderNum = this.purchaseOrder.purchaseOrderNum;
      });
      console.log(this.purchaseOrder);
       this.PurchaseService.addPurchaseOrder(this.purchaseOrder).subscribe(
        (res: any) => {
          if (this.isStartApproval) {
            this.ReviewFlowService.StartApprovalFlow('采购订单审核流配置', [
              this.purchaseOrder.purchaseOrderNum,
            ]).subscribe(
              (data: any) => {
                this.showToast('success', '成功', '流程发起成功');
                setTimeout(() => {
                  this.cancel();
                }, 1000);
              },
              (error: any) => {
                this.showToast('error', '失败', error.error);
                setTimeout(() => {
                  this.cancel();
                }, 1000);
              }
            );
          } else {
            this.showToast('success', '成功', '提交成功');
            setTimeout(() => {
              this.cancel();
            }, 1000);
          }
        },
        (error) => {
          if (error.status == 404) {
            this.showToast('error', '失败', '服务器连接失败');
          } else {
            this.showToast('error', '失败', error.error);
          }
        }
      );
    } else {
      this.showToast('warn', '错误', '请检查表单是否填写正确');
    }
  }
  getImagesArray(fileURL: string): string[] {
    let urls = fileURL.split(',');
    urls = urls.map((url) => environment.modifiedApiUrl + url);
    return urls;
  }
  cancel() {
    this.Router.navigateByUrl('/pages/purchase/purchase-order');
  }
  fujian(dialogtype?: string) {
    const results = this.DialogService.open({
      title: '采购订单附件',
      width: '800px',
      backdropCloseable: false,
      data: {
        data: '销售附件',
        urls: this.purchaseOrder.files,
      },
      content: AttachmentComponent,
      dialogtype: dialogtype,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.purchaseOrder.files.push(results.modalContentInstance.urls);
            this.fujianNumber = this.purchaseOrder.files.length;
            results.modalInstance.hide();
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  validateSalesQuotation(purchaseOrder: PurchaseOrder): boolean {
    for (const [index, item] of purchaseOrder.purchaseOrderParts.entries()) {
      if (!item.partNum) {
        this.showToast('warn', '错误', `第${index + 1}行物料编码不能为空`);
        return false;
      }
      if (item.purchaseQuantity <= 0) {
        this.showToast('warn', '错误', `第${index + 1}行采购数量必须大于0`);
        return false;
      }
      if (item.estimatedDeliveryDate == null) {
        this.showToast('warn', '错误', `第${index + 1}行预计到货日期不能为空`);
        return false;
      }
      if (item.priceWithTax == 0) {
        this.showToast('warn', '错误', `第${index + 1}行单价(含税)不能为空`);
        return false;
      }
    }
    return true;
  }
  selectLogistics() {
    const currentLogistics = this.purchaseOrder.logisticsCompanyCode ? {
      logisticsCode: this.purchaseOrder.logisticsCompanyCode,
      companyName: this.purchaseOrder.logisticsCompanyName,
      contactName: this.purchaseOrder.logisticsContactName,
      contactPhone: this.purchaseOrder.logisticsContactPhone
    } : null;

    const results = this.DialogService.open({
      id: 'select-logistics',
      width: '800px',
      maxHeight: '600px',
      title: '选择物流公司',
      content: SelectLogisticsComponent,
      backdropCloseable: true,
      data: {
        currentLogistics: currentLogistics
      },
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            const selectedItem = results.modalContentInstance.selectedItem;
            if (selectedItem) {
              this.purchaseOrder.logisticsCompanyCode = selectedItem.logisticsCode;
              this.purchaseOrder.logisticsCompanyName = selectedItem.companyName;
              this.purchaseOrder.logisticsContactName = selectedItem.contactName;
              this.purchaseOrder.logisticsContactPhone = selectedItem.contactPhone;
            } else {
              // 如果没有选择，清空物流信息
              this.purchaseOrder.logisticsCompanyCode = '';
              this.purchaseOrder.logisticsCompanyName = '';
              this.purchaseOrder.logisticsContactName = '';
              this.purchaseOrder.logisticsContactPhone = '';
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectUser() {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: '',
      title: '选择业务员',
      content: SelectUserComponent,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.purchaseOrder.purchaseManName =
              results.modalContentInstance.selectData.name;
            this.purchaseOrder.purchaseManId =
              results.modalContentInstance.selectData.id;
            this.UserService.GetDepartmentById(
              results.modalContentInstance.selectData.departmentId
            ).subscribe((res: any) => {
              this.purchaseOrder.departmentName = res.name;
              this.purchaseOrder.departmentId = res.departmentId;
            });
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectDepartment() {
    if (!this.purchaseOrder.purchaseManId) {
      this.showToast('warn', '请选择申请人', '请选择申请人');
    }
  }
  selectSupply(reset?: boolean) {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: '',
      title: '选择供应商',
      content: SelectSupplierComponent,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.purchaseOrder.supplyShortName =
              results.modalContentInstance.selectData.supplyShortName;
            this.purchaseOrder.poSupplyId =
              results.modalContentInstance.selectData.supplyId;
            this.purchaseOrder.supplyChineseName =
              results.modalContentInstance.selectData.supplyChineseName;
            this.purchaseOrder.supplyEnglishName =
              results.modalContentInstance.selectData.supplyEnglishName;
            this.supplyContactOption =
              results.modalContentInstance.selectData.supplyContacts;
            this.purchaseOrder.purchaseManName =
              results.modalContentInstance.selectData.salesmanName;
            this.purchaseOrder.purchaseManId =
              results.modalContentInstance.selectData.salesmanId;
              this.purchaseOrder
              this.purchaseOrder.supplyNum = results.modalContentInstance.selectData.supplyNum;
            this.UserService.GetUserById(
              results.modalContentInstance.selectData.salesmanId
            ).subscribe((res: any) => {
              this.purchaseOrder.departmentId = res.departmentId;
              this.UserService.GetDepartmentById(res.departmentId).subscribe(
                (res: any) => {
                  this.purchaseOrder.departmentName = res.name;
                }
              );
            });
            this.defaultTaxRate =
              results.modalContentInstance.selectData.taxRate;
            this.purchaseOrder.supplyContactId =
              results.modalContentInstance.selectData.supplyContacts.find(
                (contact: { isDefault: boolean }) => contact.isDefault === true
              )?.supplyContactId;
            this.purchaseOrder.supplyContactName =
              results.modalContentInstance.selectData.supplyContacts.find(
                (contact: { isDefault: boolean }) => contact.isDefault === true
              )?.supplyContactName;
            results.modalInstance.hide();
            this.supplyContact = {
              supplyContactId: this.purchaseOrder.supplyContactId,
              supplyContactName: this.purchaseOrder.supplyContactName,
            };
            this.currency = {
              currencyId:
                results.modalContentInstance.selectData.supplyCurrencyId,
              currencyName:
                results.modalContentInstance.selectData.currencyName,
            };
            this.settlementMethod = {
              settlementMethodId:
                results.modalContentInstance.selectData
                  .supplySettlementMethodId,
              settlementMethodName:
                results.modalContentInstance.selectData.settlementMethodName,
            };
            this.collectionPeriod = {
              collectionPeriodId:
                results.modalContentInstance.selectData
                  .supplyCollectionPeriodId,
              collectionPeriodName:
                results.modalContentInstance.selectData.collectionPeriodName,
            };
            this.purchaseOrder.supplySettlementMethodId =
              results.modalContentInstance.selectData.supplySettlementMethodId;
            this.purchaseOrder.settlementMethodName =
              results.modalContentInstance.selectData.settlementMethodName;
            this.purchaseOrder.supplyCurrencyId =
              results.modalContentInstance.selectData.supplyCurrencyId;
            this.purchaseOrder.currencyName =
              results.modalContentInstance.selectData.currencyName;
            this.purchaseOrder.supplyCollectionPeriodId =
              results.modalContentInstance.selectData.supplyCollectionPeriodId;
            this.purchaseOrder.collectionPeriodName =
              results.modalContentInstance.selectData.collectionPeriodName;
            if (reset) {
              this.purchaseOrder.purchaseOrderParts = [
                {
                  purchaseOrderPartId: null, // 采购订单物料行ID
                  partNum: '', // 物料编号
                  partUOM: '', // 物料单位
                  partName: '', // 物料名称
                  description: '', // 物料描述
                  partType: '', // 规格型号
                  image: '', // 图片
                  purchaseQuantity: 0, // 采购数量
                  realTimeInventory: 0, // 实时库存
                  estimatedDeliveryDate: null, // 预计到货日期
                  priceWithTax: 0, // 单价（含税）
                  priceWithoutTax: 0, // 单价（不含税）
                  taxRate: 0, // 税率
                  amountWithTax: 0, // 含税金额
                  amountWithoutTax: 0, // 不含税金额
                  taxAmount: 0, // 税额
                  poPartId: 0, // 物料ID
                  receivedQuantity: 0, // 已入库数
                  noReceivedQuantity: 0, // 未入库数
                  deliveryQuantity: 0, // 已到货数
                  note: '', // 备注
                  purchasereQuireNum: '', // 来源采购订单单号
                  purchaseRequiredOrderPartId: 0, // 采购订物料行ID
                  poPurchaseOrderId: 0, // 采购订单ID
                  purchaseOrderNum: '',
                  isInspection: false,
                  qrCodePath: ''
                },
              ];
            }
            this.purchaseOrder.purchaseOrderParts.forEach((item) => {
              item.taxRate = this.defaultTaxRate;
              this.calculateAmount(item);
            });
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectSupplyBefore(dialogtype?: string) {
    if (
      this.purchaseOrder.purchaseOrderParts[0].partNum &&
      this.purchaseOrder.supplyChineseName
    ) {
      const results = this.DialogService.open({
        id: 'dialog-service',
        maxHeight: '400px',
        width: '300px',
        backdropCloseable: true,
        data: '',
        title: '',
        dialogtype: dialogtype,
        html: true,
        content:
          '<div style="color:#8a6d3b;font-size: 14px;">确定切换供应商，这将会使您构建的物料行数据重置！</div>',
        onClose: () => {},
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              results.modalInstance.hide();
              this.selectSupply(true);
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    } else {
      this.selectSupply();
    }
  }
  selectSupplyContact($event: any) {
    this.purchaseOrder.supplyContactId = $event.supplyContactId;
    this.purchaseOrder.supplyContactName = $event.supplyContactName;
  }
  selectcurrency($event: any) {
    this.purchaseOrder.supplyCurrencyId = $event.currencyId;
    this.purchaseOrder.currencyName = $event.currencyName;
  }
  selectsettlementMethodOption($event: any) {
    this.purchaseOrder.supplySettlementMethodId = $event.settlementMethodId;
    this.purchaseOrder.settlementMethodName = $event.settlementMethodName;
  }
  selectcollectionPeriodOption($event: any) {
    this.purchaseOrder.supplyCollectionPeriodId = $event.collectionPeriodId;
    this.purchaseOrder.collectionPeriodName = $event.collectionPeriodName;
  }
  taxRateChange(rowitem: any, value: number) {
    rowitem.taxRate = value / 100;
    this.calculateAmount(rowitem);
  } //税率改变
  purchaseQuantityChange(rowitem: any, value: number) {
    rowitem.purchaseQuantity = value;
    this.calculateAmount(rowitem);
  } //采购数量改变
  priceWithTaxChange(rowitem: any, value: number) {
    rowitem.priceWithTax = value;
    this.calculateAmount(rowitem);
  }
  calculateAmount(item: any): void {
    //计算不含税单价，并保留6位小数
    item.priceWithoutTax = +(item.priceWithTax / (1 + item.taxRate)).toFixed(4);
    item.amountWithTax = +(item.priceWithTax * item.purchaseQuantity).toFixed(
      4
    );
    item.taxAmount = +(
      (item.priceWithTax - item.priceWithoutTax) *
      item.purchaseQuantity
    ).toFixed(4);
    item.amountWithoutTax = +(item.amountWithTax - item.taxAmount).toFixed(4);
    this.calculateTotalAmount();
  }
  calculateTotalAmount(): void {
    // 重置总计属性
    this.purchaseOrder.totalPurchaseQuantity = 0;
    this.purchaseOrder.totalaMountWithTax = 0;
    this.purchaseOrder.totalTaxAmount = 0;
    this.purchaseOrder.totalAmountWithoutTax = 0;

    // 遍历并累加各项值
    this.purchaseOrder.purchaseOrderParts.forEach((item) => {
      this.purchaseOrder.totalPurchaseQuantity += item.purchaseQuantity;
      this.purchaseOrder.totalaMountWithTax += item.amountWithTax;
      this.purchaseOrder.totalTaxAmount += item.taxAmount;
      this.purchaseOrder.totalAmountWithoutTax += item.amountWithoutTax;
    });
    // 保留6位小数
    this.purchaseOrder.totalPurchaseQuantity = parseFloat(
      this.purchaseOrder.totalPurchaseQuantity.toFixed(6)
    );
    this.purchaseOrder.totalaMountWithTax = parseFloat(
      this.purchaseOrder.totalaMountWithTax.toFixed(6)
    );
    this.purchaseOrder.totalTaxAmount = parseFloat(
      this.purchaseOrder.totalTaxAmount.toFixed(6)
    );
    this.purchaseOrder.totalAmountWithoutTax = parseFloat(
      this.purchaseOrder.totalAmountWithoutTax.toFixed(6)
    );
  }
  selectRequirement(dialogtype?: string) {
    const purchaseRequiredOrderPartIds =
      this.purchaseOrder.purchaseOrderParts.map(
        (part) => part.purchaseRequiredOrderPartId
      );
    const results = this.DialogService.open({
      id: 'Add',
      width: '1200px',
      maxHeight: '600px',
      backdropCloseable: true,
      data: {
        purchaseRequiredOrderPartIds: purchaseRequiredOrderPartIds,
        type: '新增',
      },
      title: '选择采购需求',
      content: SelectRequireComponent,
      dialogtype: dialogtype,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            // 现有的 purchaseOrderParts 数组
            const existingPurchaseOrderParts =
              this.purchaseOrder.purchaseOrderParts.filter(
                (item: any) => item.poPartId !== 0 && item.poPartId !== null
              );
            const newPurchaseOrderParts =
              results.modalContentInstance.filterRows.map((item: any) => {
                return {
                  purchaseOrderPartId: null, // 采购订单物料行ID
                  partNum: item.partNum, // 物料编号
                  partUOM: item.partUOM, // 物料单位
                  partName: item.partName, // 物料名称
                  description: item.description, // 物料描述
                  partType: item.partType, // 规格型号
                  image: item.image, // 图片
                  purchaseQuantity:
                    item.purchaseQuantity - item.orderedQuantity, // 采购数量
                  realTimeInventory: 0, // 实时库存
                  estimatedDeliveryDate: new Date(item.purchaseDate), //预计到货日期
                  priceWithTax: 0, // 单价（含税）
                  priceWithoutTax: 0, // 单价（不含税）
                  taxRate: this.defaultTaxRate, // 税率
                  amountWithTax: 0, // 含税金额
                  amountWithoutTax: 0, // 不含税金额
                  taxAmount: 0, // 税额
                  poPartId: item.propPartId, // 物料ID
                  receivedQuantity: 0, // 已入库数
                  noReceivedQuantity: 0, // 未入库数
                  deliveryQuantity: 0, // 已到货数
                  note: '', // 备注
                  purchasereQuireNum: item.purchaseRequiredNum, // 来源采购订单单号
                  poPurchaseOrderId: this.purchaseOrder.purchaseOrderId, // 采购订单ID
                  purchaseRequiredOrderPartId: item.purchaseRequiredOrderPartId, // 采购订物料行ID
                  isInspection: item.isInspection,
                  qrCodePath: ''
                };
              });

            // 合并现有的和新的 purchaseOrderParts 数组
            this.purchaseOrder.purchaseOrderParts =
              existingPurchaseOrderParts.concat(newPurchaseOrderParts);
            this.purchaseOrder.purchaseOrderParts.forEach((item) => {
              this.SupplierPriceService.getVaildPriceByPartId(
                item.poPartId
              ).subscribe((res: any) => {
                item.priceWithTax = res[0].price;
                this.calculateAmount(item);
              });
              this.StorehouseService.GetPartsAllInventory([
                item.poPartId,
              ]).subscribe((res: any) => {
                item.realTimeInventory = res[0].inventory;
              });
              this.calculateAmount(item);
            });
            if (this.purchaseOrder.purchaseOrderParts.length == 0) {
              this.addRow();
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
}
